<?php

namespace App\Services;

use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use common\utils\ValidateCode;
use common\utils\SysCode;
use App\Models\UserProperty;
use common\utils\RSACrypt;
use common\utils\Encrypt;

class UserPropertyService
{
    public static $validColumn = ['nickname', 'avatar_url', 'birth', 'sex', 'qq', 'wechat', 'skype'];

    public static function info($id)
    {
        $profile = (array)DB::table('user as u')->leftJoin('user_property as p', 'u.id', '=', 'p.user_id')
            ->select([
                'u.username',
                'u.email',
                'u.mobile',
                'p.nickname',
                'p.avatar_url',
                'p.birth',
                'p.sex',
                'p.qq',
                'p.wechat',
                'p.skype',
            ])->where(['u.id' => $id])->first();
        $profile = RSACrypt::rsaPatch($profile);
        return $profile;
    }

    public static function modify($id, $attrs)
    {
        $attrs = RSACrypt::rsaPatch($attrs, Encrypt::ENCRYPT);
        // 过滤字段
        foreach ($attrs as $k => $v) {
            if (!in_array($k, self::$validColumn)) {
                error_exit(SysCode::INVALID_ARGUMENT);
            }
        }
        return UserProperty::where(['user_id' => $id])->update($attrs);
    }

    public static function getFieldsValue($id, $field)
    {
        $property = UserProperty::select($field)->where('user_id', $id)->first()->toArray();
        if(!$property){
            return false;
        }
        if(is_array($field)){
            return RSACrypt::rsaPatch($property);
        }else{
            return RSACrypt::rsaDecrypt($property[$field]);
        }
    }
}
